package com.chengqs.dfs.backupnode.server;

import com.alibaba.fastjson.JSONArray;
import com.chengqs.dfs.namenode.rpc.model.FetchEditsLogRequest;
import com.chengqs.dfs.namenode.rpc.model.FetchEditsLogResponse;
import com.chengqs.dfs.namenode.rpc.model.UpdateCheckpointTxidRequest;
import com.chengqs.dfs.namenode.rpc.model.UpdateCheckpointTxidResponse;
import com.chengqs.dfs.namenode.rpc.service.NameNodeServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.netty.NegotiationType;
import io.grpc.netty.NettyChannelBuilder;

/**
 * <B>主类名称：</B>NameNodeRpcClient<BR>
 * <B>概要说明：</B>enter<BR>
 *
 * @author: chengqs
 * @create: 2025-03-31 21:13:20
 **/
public class NameNodeRpcClient {
    private static final String NAME_NODE_HOSTNAME = "localhost";
    private static final int NAME_NODE_PORT = 50070;

    private final NameNodeServiceGrpc.NameNodeServiceBlockingStub nameNode;

    private boolean isNameNodeRunning = true;

    public NameNodeRpcClient() {
        ManagedChannel channel = NettyChannelBuilder
                .forAddress(NAME_NODE_HOSTNAME, NAME_NODE_PORT)
                .negotiationType(NegotiationType.PLAINTEXT)
                .build();
        this.nameNode = NameNodeServiceGrpc.newBlockingStub(channel);
    }

    /**
     * 抓取editsLog数据
     * @return
     */
    public JSONArray fetchEditsLog(long syncedTxid) {
        FetchEditsLogRequest request = FetchEditsLogRequest.newBuilder()
                .setSyncedTxid(syncedTxid)
                .build();

        FetchEditsLogResponse response = nameNode.fetchEditsLog(request);
        String editsLogJson = response.getEditsLog();

        return JSONArray.parseArray(editsLogJson);
    }

    public void updateCheckpointTxid(long checkpointTxid) {
        UpdateCheckpointTxidRequest request = UpdateCheckpointTxidRequest.newBuilder()
                .setTxid(checkpointTxid)
                .build();

        UpdateCheckpointTxidResponse response = nameNode.updateCheckpointTxid(request);
    }

    public boolean isNameNodeRunning() {
        return isNameNodeRunning;
    }

    public void setNameNodeRunning(boolean nameNodeRunning) {
        isNameNodeRunning = nameNodeRunning;
    }
}
